/*
 * @Author: xiaopang
 * @Date: 2025-10-16 11:25:18
 * @LastEditTime: 2025-10-16 11:25:33
 * @LastEditors: xiaopang
 */
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null);
  const token = ref('');
  const isLogin = ref(false);

  // 计算属性
  const getUserName = computed(() => userInfo.value?.name || '');
  const isLoggedIn = computed(() => isLogin.value && !!token.value);

  // 方法
  const setUserInfo = info => {
    userInfo.value = info;
    isLogin.value = true;
  };

  const setToken = newToken => {
    token.value = newToken;
  };

  const login = (info, newToken) => {
    setUserInfo(info);
    setToken(newToken);
  };

  const logout = () => {
    userInfo.value = null;
    token.value = '';
    isLogin.value = false;
  };

  return {
    // 状态
    userInfo,
    token,
    isLogin,
    // 计算属性
    getUserName,
    isLoggedIn,
    // 方法
    setUserInfo,
    setToken,
    login,
    logout
  };
});
